// Simulate config options from your production environment by
// customising the .env file in your project's root folder.
require('dotenv').config();
var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;

delete process.env["DEBUG_FD"];
// Require keystone
var keystone = require('keystone');
var handlebars = require('express-handlebars');
var MessageService = require('./service/MessageService');
// Initialise Keystone with your project's configuration.
// See http://keystonejs.com/guide/config for available options
// and documentation.

keystone.init({
	'name': 'KVW',
	'brand': 'KVW',
	'less': 'public',
	'static': ['public','build'],
	'compress':true,
	'favicon': 'public/favicon.ico',
	'views': 'templates/views',
	'view engine': 'hbs',
	'custom engine': handlebars.create({
		layoutsDir: 'templates/views/layouts',
		partialsDir: 'templates/views/partials',
		defaultLayout: 'default',
		helpers: new require('./templates/views/helpers')(),
		extname: '.hbs',
	}).engine,

	'auto update': true,
	'session': true,
	// 'session store':'connect-redis',
	// 'sessionStore': {
	// 	"host": "127.0.0.1", // Redis服务器主机名
	// 	"port": "6379", // Redis服务器端口
	// 	"ttl": "10800", // 以秒为单位的Redis会话TTL
	// 	"db": "", // 所用的数据库索引
	// 	"pass": "", // 用于Redis认证的密码
	// 	"prefix": "", // Key前缀默认为"sess:"
	// 	"url": "", // 比如 redis://user:pass@host:port/db
	// },
	'auth': true,
	'user model': 'User',
});

// Load your project's Models
keystone.import('models');

// Setup common locals for your templates. The following are required for the
// bundled templates and layouts. Any runtime locals (that should be set uniquely
// for each request) should be added to ./routes/middleware.js
keystone.set('locals', {
	_: require('lodash'),
	env: keystone.get('env'),
	utils: keystone.utils,
	editable: keystone.content.editable,
});

// Load your project's Routes
keystone.set('routes', require('./routes'));


// Switch Keystone Email defaults to handlebars
// keystone.Email.defaults.templateExt = 'hbs';
// keystone.Email.defaults.templateEngine = require('handlebars');


// Configure the navigation bar in Keystone's Admin UI
keystone.set('nav', {
	posts: ['posts', 'post-categories'],
	galleries: 'galleries',
	enquiries: 'enquiries',
	users: 'users',
});
// Start Keystone to connect to your database and initialise the web server
if(process.env.NODE_ENV === 'production'){
	if (cluster.isMaster) {
		console.log("master start...");

		// Fork workers.
		for (var i = 0; i < numCPUs; i++) {
			cluster.fork();
		}

		cluster.on('listening',function(worker,address){
			console.log('listening: worker ' + worker.process.pid +', Address: '+address.address+":"+address.port);
		});

		cluster.on('exit', function(worker, code, signal) {
			console.log('worker ' + worker.process.pid + ' died');
		});
	} else {
		keystone.start();
	}

}else {
	keystone.start();
}


// MessageService.init(keystone);
